package face.pay.cpn.card.service.impl;

import com.github.wxpay.sdk.WXPayUtil;
import face.pay.cpn.AbstractApiService;
import face.pay.cpn.card.param.GetCardParam;
import face.pay.cpn.card.service.IGetCpnCardService;
import face.pay.cpn.mchinfo.service.INewMchListService;
import face.pay.cpn.utils.request.RequestParam;
import face.pay.cpn.utils.response.ErrorCode;
import face.pay.cpn.utils.response.ResponseMessage;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.util.AESUtils;
import face.pay.util.DateUtil;
import face.pay.util.MathUtil;
import face.pay.util.bean.JavaBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 优惠券领取
 */
@Service
@Slf4j
public class GetCpnCardServiceImpl extends AbstractApiService implements IGetCpnCardService {

    @Autowired
    CpnCardInfoDao cpnCardInfoDao;

    /**
     *
     */
    @Autowired
    CpnMarketSourcesConfigDao cpnMarketSourcesConfigDao;

    @Autowired
    CpnActivityInfoDao cpnActivityInfoDao;

    @Autowired
    CpnCardDetailInfoDao cpnCardDetailInfoDao;

    /**
     *
     */
    @Autowired
    CpnMchServiceInfoDao cpnMchServiceInfoDao;

    @Override
    public ResponseMessage getCpnCard(String info) {
        return this.doApi(info);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseMessage doService(CpnMarketInfo cpnMarketInfo, RequestParam requestParam) throws Exception {
        log.info("执行优惠券领取业务");
        Map<String, String> data = requestParam.getData();

        GetCardParam getCardParam = (GetCardParam) JavaBeanUtils.mapToBean(data, GetCardParam.class);

        String security_key = cpnMarketInfo.getSecurity_key();
        Long cpnCardId = getCardParam.getCpnCardId();

        log.info("查找优惠券");
        CpnCardInfo cpnCardInfo = this.cpnCardInfoDao.getAvailableCardById(cpnCardId);

        if (cpnCardInfo != null) {
            log.info("查找优惠券信息" + cpnCardInfo.toString());

            String bizCode = getCardParam.getBizCode();
            if (StringUtils.isBlank(bizCode)) {
                bizCode = "0";
            }

            Integer marketId = cpnMarketInfo.getId();

            String cpnCode = UUID.randomUUID().toString();

            Integer oemId = cpnCardInfo.getOemId();

            Integer mchUserId = cpnCardInfo.getUserId();

            Integer merchant_id = cpnCardInfo.getMerchant_id();


            Integer activityId = cpnCardInfo.getActivityId();


            /**
             * 打折力度
             */
            Double disCount = cpnCardInfo.getDiscount();

            /**
             *判断库存 以后实现
             */
            CpnMarketSourcesConfig sourcesConfig =
                    this.cpnMarketSourcesConfigDao.queryCpnMarketSourcesConfig(
                            new CpnMarketSourcesConfig(oemId, marketId));
            if (sourcesConfig != null) {
                log.info("获取配资源配置信息" + sourcesConfig.toString());

                if (new Integer(1).equals(sourcesConfig.getStatus())) {

                    CpnCardDetailInfo cpnCardDetailInfo = new CpnCardDetailInfo(
                            oemId, mchUserId, cpnCardId, cpnCode, marketId, merchant_id, 0, bizCode
                    );


                    String conver_url = sourcesConfig.getConver_url().trim();

                    conver_url += "?cpn_auth_code=" + cpnCode;
                    log.info("生成兑换链接：" + conver_url);

                    cpnCardDetailInfo.setConvertUrl(conver_url);


                    /**
                     * 商家服务费计算
                     */
                    CpnMchServiceInfo mchServiceInfo = this.cpnMchServiceInfoDao.getByUserId(mchUserId);

                    /**
                     * 商家服务费
                     */
                    Double service_fee = mchServiceInfo.getService_fee();

                    /**
                     * 优惠券平台对该投放平台开放的最优惠的服务费限制
                     *
                     */

                    Double oemFee = sourcesConfig.getOem_fee();
                    Double cpnFee = sourcesConfig.getCpn_fee();

                    Double max_service_fee = sourcesConfig.getMax_mch_fee();

                    /**
                     * marketFee= service_fee-(oemFee+cpnFee)
                     */
                    Double marketFee = MathUtil.sub(service_fee, MathUtil.add(oemFee, cpnFee));

                    if (max_service_fee.compareTo(new Double(0))==1  &&  marketFee.compareTo(max_service_fee)==1) {
                        marketFee = max_service_fee;
                    }

                    cpnCardDetailInfo.setMarketFee(marketFee);

                    /**
                     * 计算投放平台利润百分比
                     */

                    cpnCardDetailInfo.setMchFee(service_fee);


                    /**
                     * 总的利润率 为 service_fee-disCount >=0.05
                     * 才能领取成功
                     */
                    Double totalProfitFee = MathUtil.sub(service_fee, disCount);
                    log.info("总利润率："+totalProfitFee);
                    if (new Double(0.05).compareTo(totalProfitFee) <= 1) {

                        cpnCardDetailInfo.setOemFee(oemFee);
                        log.info("OEM 利润率："+oemFee);

                        cpnCardDetailInfo.setCpnFee(cpnFee);
                        log.info("CPN 利润率："+oemFee);
                        cpnCardDetailInfo.setWxCardId(cpnCardInfo.getCard_id());

                        log.info("折扣率："+disCount);

                        /**
                         * 判断market 是否有利润
                         * 有利润才能领取成功
                         * market_profit = 商家给market结算价-优惠券折扣
                         */
                        Double market_profit = MathUtil.sub(marketFee, disCount);
                        log.info("投放平台利润率："+market_profit);

                        if (market_profit.compareTo(new Double(0)) > 0) {

                            String loseTime = DateUtil.dateFormat(DateUtil.getDayLastTime(new Date()));

                            cpnCardDetailInfo.setLoseTime(loseTime);

                            Date endTime = DateUtil.addDay(new Date(), 30);
                            /**
                             * 取endTtime(最晚时间) 23;59:59
                             */
                            endTime = DateUtil.getDayLastTime(endTime);
                            CpnActivityInfo cpnActivityInfo = this.cpnActivityInfoDao.getById(activityId);

                            if(! new Integer(1).equals(cpnActivityInfo.getState())){
                                return ResponseMessage.createFail(ErrorCode.FAIL_CODE, "活动已经关闭");
                            }
                            Date activityEndTime = DateUtil.dateParse(cpnActivityInfo.getEnd_time(), DateUtil.default_pattern);


                            if (endTime.after(activityEndTime)) {
                                endTime = activityEndTime;
                            }

                            cpnCardDetailInfoDao.insert(cpnCardDetailInfo);

                            Map<String, String> resultData = new HashMap<>();
                            resultData.put("bizCode", bizCode);
                            resultData.put("conver_url", conver_url);
                            resultData.put("loseTime", loseTime);
                            resultData.put("endTime", DateUtil.dateFormat(endTime));

                            return ResponseMessage.createSuccess(resultData);
                        }else {
                            log.info("投放平台利润率 market_profit： "+market_profit+" 优惠券不能领取");

                            return ResponseMessage.createFail(ErrorCode.PROFIT_ERROR, "该优惠券当前不可领取");

                        }
                    }else {
                        log.info("总利润率 totalProfitFee"+totalProfitFee+"小于5% 优惠券不能领取");
                        return ResponseMessage.createFail(ErrorCode.PROFIT_ERROR, "该优惠券当前不可领取");
                    }
                } else {
                    return ResponseMessage.createFail(ErrorCode.AUTH_ERROR, "该渠道的优惠券已关闭");
                }
            } else {
                return ResponseMessage.createFail(ErrorCode.AUTH_ERROR, "权限不足");
            }
        } else {
            return ResponseMessage.createFail(ErrorCode.FAIL_CODE, "不存在的优惠券或优惠券已经失效");
        }
  }
}
